package multi_thread.basic;

/**
 * @author Cheng Jun
 * Description: 线程状态学习
 * @version 1.0
 * @date 2021/9/17 10:55
 * @see Thread.State
 * 非常重要
 */
public class ThreadStateExample {
    public static void main(String[] args) {
        Object lock = new Object();
        Thread thread_0 = new Thread(() -> {
            synchronized (lock) {
                try {
                    Thread.sleep(20_000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "线程状态为：" + Thread.currentThread().getState().name());
            }
        });
        Thread thread_1 = new Thread(() -> {
            synchronized (lock) {
                System.out.println(Thread.currentThread().getName() + "线程状态为：" + Thread.currentThread().getState().name());
            }
        });
        thread_0.start();
        System.out.println("thread_0: " + thread_0.getState().name());
        System.out.println("thread_0: " + thread_0.getState().name());
        System.out.println("thread_0: " + thread_0.getState().name());
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread_1.start();
        // 可以看出 thread_1 刚开始的线程状态是 RUNNABLE，后面几次输出的线程状态是 BLOCKED，因为lock锁被 thread_0持有
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());
        System.out.println("thread_1 的线程状态：" + thread_1.getState().name());

    }
}
